<?php
/**
 * Kelas untuk autentikasi user.
 *
 * Kelas ini menyediakan fitur autentikasi user ke database atau via IMAP.
 *
 * @category   Controllers
 * @package    System
 * @author     Lie Roberto Eliantono <roberto.ea@gmail.com>
 * @version    0.2.2
 */
class Authentication extends MX_Controller {

	public function __construct()
	{
		parent::__construct();
	}

	/**
	 * Menentukan method yang dipanggil ketika controller diakses
	 *
	 * Secara default, method ini akan melakukan logout jika ada user
	 * yang sedang login atau menampilkan form login jika tidak ada.
	 *
	 * @return void
	 * @access public
	 * @see logout(), show_login_form()
	 */	
	public function index()
	{
		if (!$this->session->userdata('user')) {
			$this->logout();
		} else {
			$this->show_login_form();
		}
	}
	
	/**
	 * Me-logout user
	 *
	 * Method ini akan menghapus data user dari session
	 *
	 * @return void
	 * @access public
	 */	
	public function logout() {
		$user = $this->session->userdata('user');
		$this->session->unset_userdata('user');
		$this->session->unset_userdata('user_id');
		$this->session->unset_userdata('role');
		$this->session->unset_userdata('role_desc');
		$this->common->flash_message('User <strong>'.$user.'</strong> logged out successfully', -1);
		redirect($this->referrer);
	}

	/**
	 * Melakukan login user
	 *
	 * Method ini akan melakukan autentikasi kredensial user ke database
	 * atau via IMAP ke server yang ditentukan di database dan mencatat
	 * id user dan rolenya di session apabila autentikasi berhasil
	 *
	 * @return void
	 * @access public
	 */		
	public function login() {
		$user = $this->input->post('user');
		$pass = $this->input->post('pass');
		
		if ($user) {
				$this->db->select('id, password, id_sys_user_role')->from('sys_m_user')->where(array('nkey' => $user));
				$user_data = $this->db->get()->result_array();
				if (!empty($user_data)) { // user found
					reset($user_data);
					$user_data = current($user_data);
					$user_id = $user_data['id'];
					$ref_pass = $user_data['password'];
					$role = $user_data['id_sys_user_role'];
					
					$role = $this->common->get_field_from_id('sys_x_user_role', 'key_sys_role', $role);
					$role_desc = $this->common->get_field_from_key('sys_m_role', 'description', $role);
					
					if (strcmp($pass, $ref_pass)==0) { // password match
						$this->session->set_userdata('user', $user);
						$this->session->set_userdata('user_id', $user_id);
						$this->session->set_userdata('role', $role);
						$this->session->set_userdata('role_desc', $role_desc);
						$this->common->flash_message('User <strong>'.$user.'</strong> logged in successfully', -1);
					} else { // password mismatch
						$this->common->flash_message('Invalid password', 1);
					}
				} else { // user not found
					if (strpos($user, '@') !== false) {		
/*  Kode lama dengan menggunakan host sebagai username login             
 *						$imap_user = $user;
 *						$user = substr($imap_user, 0, strpos($imap_user, '@'));
 *						$host = substr($imap_user, strpos($imap_user, '@')+1);
 */

 /*
  * Kode baru dengan dan tanpa menggunaan host sebagai username login
  */
					if (strpos($user, '@') !== false) {
						$imap_user = $user;
						$user = substr($imap_user, 0, strpos($imap_user, '@'));
						$host = substr($imap_user, strpos($imap_user, '@')+1);
					} else {
						if (ereg("^if[0-9]{5}", $user))
							$host = "students.del.ac.id";
						else
							$host = "del.ac.id";
					}
						// try IMAP authentication
						$system_user = $this->common->get_key_from_criteria('sys_m_user', array('imap_user' => $user, 'imap_host' => $host));
						$imap_server_id = $this->common->get_field_from_key('sys_m_user', 'imap_server', $system_user);
						$imap_host = $this->common->get_field_from_id('sys_m_imap', 'host', $imap_server_id);
						$imap_port = $this->common->get_field_from_id('sys_m_imap', 'port', $imap_server_id);
						$imap_protocol = $this->common->get_field_from_id('sys_m_imap', 'protocol', $imap_server_id);
						$imap_validate_cert = $this->common->get_field_from_id('sys_m_imap', 'validate_cert', $imap_server_id);
						
						if ($imap_validate_cert) {
							$imap_validate_cert = 'validate-cert';
						} else {
							$imap_validate_cert = 'novalidate-cert';
						}
						
						if ($mbox = @imap_open("{".$imap_host.":".$imap_port."/".$imap_protocol."/".$imap_validate_cert."}", $user, $pass, OP_HALFOPEN, 0)) {
							$user = $system_user;
							$user_id = $this->common->get_id_from_key('sys_m_user', $user);
							
							$role = $this->common->get_field_from_id('sys_m_user', 'id_sys_user_role', $user_id);
							$role = $this->common->get_field_from_id('sys_x_user_role', 'key_sys_role', $role);							
							$role_desc = $this->common->get_field_from_key('sys_m_role', 'description', $role);
						
							$this->session->set_userdata('user', $user);
							$this->session->set_userdata('user_id', $user_id);
							$this->session->set_userdata('role', $role);
							$this->session->set_userdata('role_desc', $role_desc);
							$this->common->flash_message('User <strong>'.$user.'</strong> logged in successfully', -1);

							imap_close($mbox);
						} else {
							$this->common->flash_message('IMAP Error: '.imap_last_error(), 1);
						}
						
					} else {
						$this->common->flash_message('Invalid user', 1);
					}
				}
		} else { // no user specified
			$this->common->flash_message('Please specify a user to login');
		}
		
		redirect($this->referrer);
	}

	/**
	 * Menampilkan form login
	 *
	 * Pada versi ini, karena login form berada di sidebar tiap layar,
	 * maka yang dilakukan hanyalah me-redirect ke referrer
	 *
	 * @return void
	 * @access public
	 */		
	function show_login_form() {
		redirect($this->referrer);
	}
}

/* EOF controllers/authentication.php */
